#include "scene_api.h"
#include "http/http_server.h"
#include "scenes/scene_manager.h"
#include "logger.h"
#include <stdlib.h>
#include <string.h>

// 从用户数据中获取系统管理器
static system_manager_t *get_system_manager(void *user_data) {
    return (system_manager_t *)user_data;
}

// 从路径中提取场景ID
static int extract_scene_id_from_path(const char *path) {
    // 路径格式：/api/scenes/{id}
    if (!path || strncmp(path, "/api/scenes/", 12) != 0) {
        return -1;
    }

    const char *id_str = path + 12;
    char *endptr;
    long id = strtol(id_str, &endptr, 10);

    if (endptr == id_str || *endptr != '\0' || id < 0) {
        return -1;
    }

    return (int)id;
}

// 验证场景数据
static bool validate_scene_data(json_t *scene_data) {
    if (!scene_data || !json_is_object(scene_data)) {
        return false;
    }

    // 检查必需字段
    json_t *name = json_object_get(scene_data, "name");
    json_t *trigger_mode = json_object_get(scene_data, "trigger_mode");
    json_t *action_type = json_object_get(scene_data, "action_type");

    if (!name || !json_is_string(name) ||
        !trigger_mode || !json_is_integer(trigger_mode) ||
        !action_type || !json_is_integer(action_type)) {
        return false;
    }

    // 检查触发方式范围
    int trigger_mode_val = json_integer_value(trigger_mode);
    if (trigger_mode_val < 1 || trigger_mode_val > 3) {
        return false;
    }

    // 检查动作类型范围
    int action_type_val = json_integer_value(action_type);
    if (action_type_val < 0 || action_type_val > 1) {
        return false;
    }

    return true;
}

http_response_t *scene_api_get_scenes(const char *method, const char *path,
                                      json_t *query_params, json_t *body,
                                      void *user_data) {
    system_manager_t *sys_mgr = get_system_manager(user_data);
    if (!sys_mgr) {
        return http_response_error(500, "System manager not available");
    }

    // 构建场景列表响应
    json_t *scenes_array = json_array();

    // 这里应该从场景管理器中获取所有场景
    // 简化实现：返回空数组
    json_t *response_json = json_object();
    json_object_set_new(response_json, "scenes", scenes_array);
    json_object_set_new(response_json, "count", json_integer(0));
    json_object_set_new(response_json, "total", json_integer(0));

    http_response_t *response = http_response_json(200, response_json);
    json_decref(response_json);

    return response;
}

http_response_t *scene_api_get_scene(const char *method, const char *path,
                                     json_t *query_params, json_t *body,
                                     void *user_data) {
    int scene_id = extract_scene_id_from_path(path);
    if (scene_id < 0) {
        return http_response_error(400, "Invalid scene ID");
    }

    system_manager_t *sys_mgr = get_system_manager(user_data);
    if (!sys_mgr) {
        return http_response_error(500, "System manager not available");
    }

    // 构建场景详情响应
    json_t *scene_json = json_object();
    json_object_set_new(scene_json, "id", json_integer(scene_id));
    json_object_set_new(scene_json, "name", json_string("示例场景"));
    json_object_set_new(scene_json, "type", json_string("环境控制"));
    json_object_set_new(scene_json, "description", json_string("示例场景描述"));
    json_object_set_new(scene_json, "enabled", json_boolean(true));
    json_object_set_new(scene_json, "trigger_mode", json_integer(2));
    json_object_set_new(scene_json, "action_type", json_integer(0));
    json_object_set_new(scene_json, "time_management", json_boolean(true));

    // 触发条件
    json_t *trigger_condition = json_array();
    json_t *condition = json_object();
    json_object_set_new(condition, "data_key", json_string("device.2.1.1"));
    json_object_set_new(condition, "operator", json_string("GT"));
    json_object_set_new(condition, "target_value", json_integer(30));
    json_object_set_new(condition, "value_type", json_string("int"));
    json_array_append_new(trigger_condition, condition);
    json_object_set_new(scene_json, "trigger_condition", trigger_condition);

    // 执行动作
    json_t *actions = json_array();
    json_t *action = json_object();
    json_object_set_new(action, "node", json_string("2"));
    json_object_set_new(action, "group", json_string("1"));
    json_object_set_new(action, "tag", json_string("10"));
    json_object_set_new(action, "value", json_integer(1));
    json_object_set_new(action, "description", json_string("开启空调"));
    json_array_append_new(actions, action);
    json_object_set_new(scene_json, "actions", actions);

    // 生效时间
    json_t *effective_time = json_object();
    json_object_set_new(effective_time, "start_time", json_string("08:00"));
    json_object_set_new(effective_time, "end_time", json_string("18:00"));

    json_t *weekdays = json_array();
    for (int i = 1; i <= 5; i++) {
        json_array_append_new(weekdays, json_integer(i));
    }
    json_object_set_new(effective_time, "weekdays", weekdays);
    json_object_set_new(scene_json, "effective_time", effective_time);

    http_response_t *response = http_response_json(200, scene_json);
    json_decref(scene_json);

    return response;
}

http_response_t *scene_api_create_scene(const char *method, const char *path,
                                        json_t *query_params, json_t *body,
                                        void *user_data) {
    if (!body || !json_is_object(body)) {
        return http_response_error(400, "Invalid request body");
    }

    system_manager_t *sys_mgr = get_system_manager(user_data);
    if (!sys_mgr) {
        return http_response_error(500, "System manager not available");
    }

    // 验证场景数据
    if (!validate_scene_data(body)) {
        return http_response_error(400, "Invalid scene data");
    }

    // 创建场景（简化实现）
    // 实际应该调用场景管理器创建场景并保存到数据库

    json_t *response_json = json_object();
    json_object_set_new(response_json, "id", json_integer(1));  // 模拟新场景ID
    json_object_set_new(response_json, "message", json_string("Scene created successfully"));

    http_response_t *response = http_response_json(201, response_json);
    json_decref(response_json);

    return response;
}

http_response_t *scene_api_update_scene(const char *method, const char *path,
                                        json_t *query_params, json_t *body,
                                        void *user_data) {
    int scene_id = extract_scene_id_from_path(path);
    if (scene_id < 0) {
        return http_response_error(400, "Invalid scene ID");
    }

    if (!body || !json_is_object(body)) {
        return http_response_error(400, "Invalid request body");
    }

    system_manager_t *sys_mgr = get_system_manager(user_data);
    if (!sys_mgr) {
        return http_response_error(500, "System manager not available");
    }

    // 验证场景数据
    if (!validate_scene_data(body)) {
        return http_response_error(400, "Invalid scene data");
    }

    // 更新场景（简化实现）
    json_t *response_json = json_object();
    json_object_set_new(response_json, "id", json_integer(scene_id));
    json_object_set_new(response_json, "message", json_string("Scene updated successfully"));

    http_response_t *response = http_response_json(200, response_json);
    json_decref(response_json);

    return response;
}

http_response_t *scene_api_delete_scene(const char *method, const char *path,
                                        json_t *query_params, json_t *body,
                                        void *user_data) {
    int scene_id = extract_scene_id_from_path(path);
    if (scene_id < 0) {
        return http_response_error(400, "Invalid scene ID");
    }

    system_manager_t *sys_mgr = get_system_manager(user_data);
    if (!sys_mgr) {
        return http_response_error(500, "System manager not available");
    }

    // 删除场景（简化实现）
    json_t *response_json = json_object();
    json_object_set_new(response_json, "message", json_string("Scene deleted successfully"));

    http_response_t *response = http_response_json(200, response_json);
    json_decref(response_json);

    return response;
}

http_response_t *scene_api_trigger_scene(const char *method, const char *path,
                                         json_t *query_params, json_t *body,
                                         void *user_data) {
    int scene_id = extract_scene_id_from_path(path);
    if (scene_id < 0) {
        return http_response_error(400, "Invalid scene ID");
    }

    system_manager_t *sys_mgr = get_system_manager(user_data);
    if (!sys_mgr) {
        return http_response_error(500, "System manager not available");
    }

    // 手动触发场景
    int result = system_manager_trigger_scene(sys_mgr, scene_id, "http_api");

    json_t *response_json = json_object();
    if (result == SUCCESS) {
        json_object_set_new(response_json, "message", json_string("Scene triggered successfully"));
        json_object_set_new(response_json, "scene_id", json_integer(scene_id));

        http_response_t *response = http_response_json(200, response_json);
        json_decref(response_json);
        return response;
    } else {
        json_object_set_new(response_json, "error", json_string("Failed to trigger scene"));
        json_object_set_new(response_json, "scene_id", json_integer(scene_id));

        http_response_t *response = http_response_json(500, response_json);
        json_decref(response_json);
        return response;
    }
}

http_response_t *scene_api_enable_scene(const char *method, const char *path,
                                        json_t *query_params, json_t *body,
                                        void *user_data) {
    int scene_id = extract_scene_id_from_path(path);
    if (scene_id < 0) {
        return http_response_error(400, "Invalid scene ID");
    }

    if (!body || !json_is_object(body)) {
        return http_response_error(400, "Invalid request body");
    }

    system_manager_t *sys_mgr = get_system_manager(user_data);
    if (!sys_mgr) {
        return http_response_error(500, "System manager not available");
    }

    json_t *enabled = json_object_get(body, "enabled");
    if (!enabled || !json_is_boolean(enabled)) {
        return http_response_error(400, "Missing or invalid 'enabled' field");
    }

    // 启用/禁用场景（简化实现）
    bool is_enabled = json_boolean_value(enabled);

    json_t *response_json = json_object();
    json_object_set_new(response_json, "scene_id", json_integer(scene_id));
    json_object_set_new(response_json, "enabled", json_boolean(is_enabled));
    json_object_set_new(response_json, "message",
                        json_string(is_enabled ? "Scene enabled" : "Scene disabled"));

    http_response_t *response = http_response_json(200, response_json);
    json_decref(response_json);

    return response;
}

int scene_api_register_routes(http_server_t *server) {
    if (!server) {
        return ERROR_INVALID_PARAM;
    }

    // 注册场景API路由
    http_server_add_route(server, "GET", "/api/scenes", scene_api_get_scenes);
    http_server_add_route(server, "POST", "/api/scenes", scene_api_create_scene);
    http_server_add_route(server, "GET", "/api/scenes/[0-9]+", scene_api_get_scene);
    http_server_add_route(server, "PUT", "/api/scenes/[0-9]+", scene_api_update_scene);
    http_server_add_route(server, "DELETE", "/api/scenes/[0-9]+", scene_api_delete_scene);
    http_server_add_route(server, "POST", "/api/scenes/[0-9]+/trigger", scene_api_trigger_scene);
    http_server_add_route(server, "PUT", "/api/scenes/[0-9]+/enable", scene_api_enable_scene);

    return SUCCESS;
}
